<template>
  <div>
    <RePage>    
            <div class="pl-[0px]">
              <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
                <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
                <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
              </MyFormCreate>
              <div>
                <el-button v-auth="'system.project-role.create'"  type="primary" :icon="Plus" @click="add">添加</el-button>
                <!-- <el-button type="danger" :icon="Delete" :disabled="!selectionData.length" @click="deletes()">批量删除</el-button> -->
              </div>
              <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
                @selection-change="selectionChange" :isShowPag="false">
                <template #action="{ row }">
                  <el-space>
                    <!-- <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link> -->
                    <sj-link custom-type="sblue" :underline="false" @click="edit(row)" v-auth="'system.project-role.modify'">编辑</sj-link>
                    <sj-link custom-type="sred" :underline="false" @click="deletes(row)" v-auth="'system.project-role.delete'">删除</sj-link>
                  </el-space>
                </template>
              </pure-table>
              <div class="mt-5">
                <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
                  :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList"
                  @current-change="getTableList" />
              </div>
            </div>
          
     
   
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import treeList from '@/components/treeList/treeList.vue'
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT, PAGE_LAYOUTLEFT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo, getAllPermission } from '@/api/manage/projectManagementes/projectrole/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
import { facilityTreeList } from '@/api/operate/project-management/projectManagement/facility-management/index';
import { getList as projectLists } from '@/api/manage/projectManagementes/projectManagementes/index';
import { usePageVariablesStoreHook, } from '@/store/modules/pageVariables'
const usePageVariablesStore = usePageVariablesStoreHook()
const IsAdd = ref(true);//是否允许添加
const projectID = ref();//用于重置时项目id不重置
const treeRef = ref();
const projectList = ref([]);
const isLoading = ref(true)
const checkedProject = ref(0);
const checkedUnitId = ref(null);
const treeListRef = ref()
const selectionData = ref([]);
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const searchFormRules = [
  {
    type: 'input', field: 'roleName', title: titles.roleName, value: null, props: {
      placeholder: prompt.roleName, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];

const roleTableConfig = [
  { prop: 'id', label: titles.id, width:  100, fixed: 'left' },
  { prop: 'unityName', label: titles.unityName, minWidth: 150 },
  { prop: 'roleName', label: titles.roleName, minWidth: 100 },
  { prop: 'updatedByName', label: titles.updatedByName, minWidth: 150 },
  { prop: 'updatedAt', label: titles.updatedAt, minWidth: 100 },



  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];

const settingLR: ContextProps = reactive({ //左右分栏
  minPercent: 17,
  maxPercent: 17,
  defaultPercent: 17,
  split: "vertical"
});
const inputProops = {   //树搜索框提示
  clearable: true,
  placeholder: "请输入项目名称"
};
const searchFrom = ref(defaultSearchForm());  //搜索框数据

const tableData = reactive({  //表格数据
  data: [],
  total: 0,
});
const projectDefultSearch = () => { // 数分页参数
  return {
    limit: 10,
    page: 1
  };
};
const treeListPage1 = ref(projectDefultSearch());// 数分页参数


onMounted(() => {//初始化
  getTableList() //表格数据
  // loadProjectList()//左侧树
  //  treeRef.value = treeListRef.value.getTreeRef();
  //   loadProjectList().then(() => {
  //     treeListRef.value.getTreeRef().setCurrentKey(projectList.value[0].id);
  //     searchFrom.value.projectId = projectList.value[0].id
  //     getTableList()
  // });
})

//ce
const props = { //树参数
  label: "projectName",
  id: "id",
  isLeaf: "isLeaf"
};

const filterMethod = (query, node) => {

  return node.projectName.includes(query);
};

//侧边栏搜索框
const inputChange = e => {
  console.log(e, 88888);
  treeListRef.value.getTreeRef().filter(e);

};
const inputEvents = {
  input: inputChange
};
//获取侧边栏数据----项目列表
const loadProjectList = () => {
  return new Promise((resolve, reject) => {
    isLoading.value = true;
    projectLists(treeListPage1.value)
      .then(res => {
        let arr = [
          {
            expireDate: "",
            id: 0,
            projectName: "全部",
            smsCount: null,
            unityName: "",
            voiceCount: null,
          }
        ]
        res.result.data.unshift(...arr);
        projectList.value = res.result.data  //侧边栏数据
        pageProops.value.total = res.result.total //侧边栏数据总数
        console.log('f', projectList.value);

      })
      .finally(() => {
        isLoading.value = false;
        resolve('');
      });

  });
};


const handleNodeClick = data => {

  projectID.value = data.id;
  searchFrom.value.projectId = data.id;
  DebounceGetTableList()

};

const treeProops = ref({
  props: props,
  data: projectList,
  nodeKey: "productId",
  'item-size': 46,
  'highlight-current': true,
  "filter-method": filterMethod
});
const pageProops = ref({
  layout: PAGE_LAYOUTLEFT,
  total: 0,
  "pager-count": "3"
})
const treeEvents = {  //树点击事件
  nodeClick: handleNodeClick,
};
const pageChange = e => {  //分页事件
  loadProjectList();
  console.log('page-change', e);

}
const pageEvents = { //分页事件
  change: pageChange
};
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键

  Object.assign(searchFrom.value, defaultSearchForm())
  searchFrom.value.projectId = projectID.value //重置时项目id不重置
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑项目角色", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加项目角色", row?: any) => {

  addDialog({
    title: `${title}`,
    width: "1100px",
    draggable: true,
    props: {
      isLoading: false,
      formInline: defaultInfoForm(),
      getAllPermission: getAllPermission
    },
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {//编辑
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm(),
          getAllPermission: getAllPermission
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            console.log("g",res);
            
            showInfo.value = res.result
            options.props.formInline = res.result
            formRef.value.reList()
          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {//新增
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm(),
          getAllPermission: getAllPermission
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.unityId = usePageVariablesStore.getManage().unityId
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加项目角色") {
            searchFrom.value.projectId = projectID.value
            DebounceAddInfo({ ...formData, projectId: searchFrom.value.projectId }).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped>
.split-pane {
  width: 100%;
  // height: calc(100vh - 200px);
  //   font-size: 50px;
  //   text-align: center;
  //   border: 1px solid #e5e6eb;

  //   .dv-a {
  //     padding-top: 0vh;
  //     color: rgba($color: dodgerblue, $alpha: 80%);
  //   }

  //   .dv-b {
  //     padding-top: 0vh;
  //     color: rgba($color: #000, $alpha: 80%);
  //   }

  //   .dv-c {
  //     padding-top: 0vh;
  //     color: rgba($color: #ce272d, $alpha: 80%);
  //   }
}
</style>
